package mapper

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"ksd-social-api/commons/page"
	"ksd-social-api/modules/special/model"
	"ksd-social-api/modules/special/model/context"
)

type AdminSpecialMapper struct {
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存用户
 */
func (service *AdminSpecialMapper) SaveUpdateSpecial(special model.Special) (dbspecial *model.Special) {
	// 创建orm对象
	mysql := orm.NewOrm()
	// 保存用户
	if special.Id > 0 {
		_, err := mysql.Update(&special)
		if err == nil {
			return &special
		}
		return nil
	} else {
		_, err := mysql.Insert(&special)
		if err == nil {
			return &special
		}
		return nil
	}
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据用户id查询用户明细
 */
func (mapper *AdminSpecialMapper) GetSpecialByID(id uint64, systemId uint64) *model.Special {
	// 创建orm对象
	mysql := orm.NewOrm()
	var special model.Special
	err := mysql.Raw("select * from xk_special where id = ? and system_id = ?").SetArgs(id, systemId).QueryRow(&special)
	if err != nil {
		return nil
	}
	return &special
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据用户id查询用户明细
 */
func (mapper *AdminSpecialMapper) UpdateFieldById(id uint64, field string, value any, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw(fmt.Sprintf("update xk_special set %s='%v',update_time=now() where id = ? and system_id = ?", field, value)).SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-12
 * @version 1.0
 * @desc 查询小册分页
 */
func (mapper *AdminSpecialMapper) FindSpecialListAndPage(ctx context.SpecialSearchContext) (p *page.Page) {
	// 1：准备容器对象，开始装载数据库数据
	specialList := []model.Special{}
	// 2：创建orm对象
	mysql := orm.NewOrm()
	cond := orm.NewCondition()
	// 3: 开始执行sql查询
	qs := mysql.QueryTable("xk_special")
	// 4: 设定两个条件
	cond = cond.
		And("system_id", ctx.SystemId).And("is_deleted", 0)
	// 5 : 判断分类是否传递如果不是""或者不是0就开始拼接条件
	if ctx.CategoryPid > 0 {
		cond = cond.And("category_id", ctx.CategoryPid)
	}
	if ctx.CategoryCid > 0 {
		cond = cond.And("category_id", ctx.CategoryCid)
	}
	if ctx.PayFlag > 0 {
		cond = cond.And("pay_flag", ctx.PayFlag)
	}
	if ctx.PushFlag > 0 {
		cond = cond.And("push_flag", ctx.PushFlag)
	}
	if ctx.HotFlag > 0 {
		cond = cond.And("hot_flag", ctx.HotFlag)
	}
	if ctx.NewFlag > 0 {
		cond = cond.And("new_flag", ctx.NewFlag)
	}
	if ctx.Specialtype > 0 {
		cond = cond.And("specialtype", ctx.Specialtype)
	}
	// 如果用户输入的搜索关键词
	if len(ctx.Keyword) > 0 {
		cond1 := orm.NewCondition()
		cond1 = cond1.Or("tags__icontains", ctx.Keyword).Or("title__icontains", ctx.Keyword)
		cond = cond.AndCond(cond1)
	}

	// 6：执行count查询
	total, err1 := qs.SetCond(cond).Count()
	if err1 != nil {
		return nil
	}
	// 4: 重新换算分页和规则
	page := p.Page(ctx.PageNo, ctx.PageSize, total)
	// 5: 执行sql---count(1)---获得具体数据  10 0/ 10 10 / 10  20/  10 30
	querySeter := qs.SetCond(cond)
	if ctx.OrderNum == 0 { // 最新
		querySeter = querySeter.OrderBy("-create_time")
	} else if ctx.OrderNum == 1 { // 最热
		querySeter = querySeter.OrderBy("-viewcount")
	} else if ctx.OrderNum == 2 { // 最后更新
		querySeter = querySeter.OrderBy("-update_time")
	} else if ctx.OrderNum == 3 { // 最后更新
		querySeter = querySeter.OrderBy("sorted")
	}
	_, err2 := querySeter.Limit(page.PageSize, page.CurrentPage).All(&specialList,
		"id",
		"title",
		"tags",
		"pan_pwd",
		"try_link",
		"specialtype",
		"description",
		"viewcount",
		"create_time",
		"update_time",
		"comment_flag",
		"is_deleted",
		"avatar",
		"nickname",
		"status",
		"userid",
		"img",
		"fav_num",
		"comment_num",
		"price",
		"realprice",
		"new_flag",
		"hot_flag",
		"push_flag",
		"category_id",
		"category_name",
		"uuid",
		"like_num",
		"path",
		"stimer",
		"pay_flag",
		"buy_num")
	// 6：把查询的数据放入到分页的records字段，准备返回
	page.Records = specialList
	// 7: 如果没有找到直接返回
	if err2 != nil {
		return nil
	}
	return page
}

/**
 * @author feige
 * @date 2023-10-12
 * @version 1.0
 * @desc 查询小册分页
 */
func (mapper *AdminSpecialMapper) FindSpecialCodePage(ctx context.CodeSearchContext) (p *page.Page) {
	// 1：准备容器对象，开始装载数据库数据
	specialCodeList := []model.SpecialCode{}
	// 2：创建orm对象
	mysql := orm.NewOrm()
	cond := orm.NewCondition()
	// 3: 开始执行sql查询
	qs := mysql.QueryTable("xk_special_code")
	// 4: 设定两个条件
	cond = cond.
		And("system_id", ctx.SystemId)
	if ctx.Mark > -1 {
		cond = cond.And("mark", ctx.Mark)
	}
	if len(ctx.Keyword) > 0 {
		cond = cond.And("code", ctx.Keyword)
	}
	// 5 : 判断分类是否传递如果不是""或者不是0就开始拼接条件
	total, err1 := qs.SetCond(cond).Count()
	if err1 != nil {
		return nil
	}
	// 4: 重新换算分页和规则
	page := p.Page(ctx.PageNo, ctx.PageSize, total)
	// 5: 执行sql---count(1)---获得具体数据  10 0/ 10 10 / 10  20/  10 30
	querySeter := qs.SetCond(cond)
	querySeter = querySeter.OrderBy("mark")
	_, err2 := querySeter.Limit(page.PageSize, page.CurrentPage).All(&specialCodeList,
		"id",
		"opid",
		"code",
		"mark",
		"system_id",
		"system_name",
		"create_time",
		"update_time",
	)
	// 6：把查询的数据放入到分页的records字段，准备返回
	page.Records = specialCodeList
	// 7: 如果没有找到直接返回
	if err2 != nil {
		return nil
	}
	return page
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存和修改兑换码
 */
func (service *AdminSpecialMapper) SaveUpdateSpecialCode(code model.SpecialCode) (dbspecial *model.SpecialCode) {
	db := orm.NewOrm()
	if code.Id > 0 {
		_, _ = db.Update(&code)
		return &code
	} else {
		_, _ = db.Insert(&code)
		return &code
	}
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  更新
 */
func (mapper *AdminSpecialMapper) UpdateFieldByCodeId(id uint64, field string, value any, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw(fmt.Sprintf("update xk_special_code set %s='%v',update_time=now() where id = ? and system_id = ?", field, value)).SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据id删除
 */
func (mapper *AdminSpecialMapper) DelById(id uint64, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw("delete from xk_special  where id = ? and system_id = ?").SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据id删除
 */
func (mapper *AdminSpecialMapper) DelCodeById(id uint64, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw("delete from xk_special_code  where id = ? and system_id = ?").SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据id删除
 */
func (mapper *AdminSpecialMapper) DelByUserorderId(id uint64, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw("delete from xk_special_user_buy  where id = ? and system_id = ?").SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据id删除
 */
func (mapper *AdminSpecialMapper) DelBindById(id uint64, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw("delete from xk_special_bind  where id = ? and system_id = ?").SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  根据id删除
 */
func (mapper *AdminSpecialMapper) DelBindDetailById(id uint64, systemId uint64) bool {
	// 创建orm对象
	mysql := orm.NewOrm()
	_, err := mysql.Raw("delete from xk_special_bind_detail  where id = ? and system_id = ?").SetArgs(id, systemId).Exec()
	if err != nil {
		return false
	}
	return true
}

/**
 * @author feige
 * @date 2023-10-08
 * @desc 根据id查询小册信息
 */
func (mapper *AdminSpecialMapper) GetById(id uint64, systemId uint64) *model.Special {
	// 1: 创建一个数据连接
	db := orm.NewOrm()
	// 2: 赋予id给结构体
	data := model.Special{Id: id, SystemId: systemId}
	// 3: 读取id的数据放入到结构体，进行返回
	_ = db.Read(&data, "id", "system_id")
	// 4: 结构返回
	return &data
}
